import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import TodoListAdd from '../components/TodoListAdd/index.jsx';
import TodoListShow from '../components/TodoListShow/index.jsx';
import TodoFilter from '../components/TodoFilter/index.jsx';
import {
  todoCreate,
  todoDelete,
  todoEditor,
  todoStateChange,
  todoFilter
} from '../actions';
import {
  ALL,
  DONE,
  UNDO
} from '../constants/actionTypes';

class homeContainer extends React.Component {

  static propTypes = {
    value: PropTypes.array.isRequired,
    dispatch: PropTypes.func.isRequired,
    showFilter: PropTypes.oneOf([
      ALL,
      DONE,
      UNDO
    ]).isRequired
  }

  componentDidMount() {
  }

  render() {

    const { dispatch, value, showFilter } = this.props;

    return (
      <div>
        <TodoListAdd _onAddClick = {text => { dispatch(todoCreate(text));} }/>
        <TodoFilter
          filter={showFilter}
          _onFilterClick = {(fliter) => { dispatch(todoFilter(fliter));} }/>

        <TodoListShow
          listContent = {value}
          _onDeleteClick = {id => { dispatch(todoDelete(id));} }
          _onEditorClick = {(id, text) => { dispatch(todoEditor(id, text));} }
          _stateChangeClick = {(id) => { dispatch(todoStateChange(id));} }/>

      </div>
    );
  }
}

//循环拆分数据,根据完成和未完成状态分类
const dataSplit = (todoList, filter) => {

  switch (filter) {

    // 选择展示的list
    case ALL:
      return todoList;
    case DONE:
      return todoList.filter((data) => {return data.checked;});
    case UNDO:
      return todoList.filter((data) => {return !data.checked;});
    default:
  }
}

//从store获取数据和更新数据
const mapStateToProps = (state) => {
  return {
    value: dataSplit(state.todoList, state.todoState),
    showFilter: state.todoState
  };
}

export default connect(
  mapStateToProps
)(homeContainer);
